/*
 * QuoteServerStub.java
 *
 * Created on February 28, 2007, 10:55 AM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package ca.uvic.group2.server;

import ca.uvic.group2.api.exceptions.*;
import ca.uvic.group2.api.*;
import ca.uvic.group2.ServerFactory;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.net.*;

/**
 *
 * @author pat
 */
public class QuoteServerStub extends UnicastRemoteObject implements QuoteServer, RemoteServer {

    private String _serverName = "QuoteServerStub";
    private AuditLog logger;
    private String serverId="QuoteServerStub";

    /** Creates a new instance of QuoteServerStub */
    public QuoteServerStub() throws CommException, RemoteException {
        super();
        logger = new ServerFactory().getAuditServer();
    }

    //
    // RemoteServer interface
    //
    private int _port;
    public void serverStart(int port) throws RemoteException, CommException {
        //debugLog.info("QuoteServer Startup on Port: " + port);
        try {
            ServerFactory.serverStart((QuoteServer) this, port, RMI_NAME);
            _port = port;
        } catch (Exception err) {
            err.printStackTrace();
            throw new CommException(err.getMessage());
        }
    }

    public void serverStop() throws RemoteException, CommException {
        //debugLog.info("QuoteServer Shutdown");
        try {

            // Perform any cleanup here

        } catch (Exception err) {
            err.printStackTrace();
            throw new CommException(err.getMessage());
        }
    }

    public void setServerName(String name) throws RemoteException {
        _serverName = name;
    }

    public String getServerName() throws RemoteException {
        return _serverName;
    }

    public String getHostName() throws RemoteException {
        try {
            return InetAddress.getLocalHost().getHostName();
        } catch (UnknownHostException err) {
            return null;
        }
    }

    //
    //
    //

    public void initSystem() throws RemoteException {
    }

    public Quote quote(int transId, String stockSymbol, String username) throws CommException, RemoteException {
        //debugLog.info("Call received to get a quote: quote()");
        Quote q = null;

        q = new Quote();
        q.expiry = System.currentTimeMillis() + 60000;
        q.key = "THIS IS AN ENCRYPED KEY";
        q.price = new Money(50.0);
        q.stock = stockSymbol;
        q.timestamp = System.currentTimeMillis();
        q.username = username;

        logger.quote(serverId, transId, q.price.doubleValue(), q.stock, q.username, q.timestamp, q.key);
        return q;
    }
}
